﻿import { createRouter, createWebHashHistory } from 'vue-router';
import { useAuthStore } from '../stores/auth';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录' },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { title: '注册' },
    },
    {
      path: '/',
      component: () => import('../views/MainLayout.vue'),
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('../views/HomeView.vue'),
          meta: { title: '课程首页' },
        },
        {
          path: 'courses/add',
          name: 'course-add',
          component: () => import('../views/AddCourseView.vue'),
          meta: { title: '新增课程', requiresAuth: true },
        },
        {
          path: 'categories/add',
          name: 'category-add',
          component: () => import('../views/AddCategoryView.vue'),
          meta: { title: '新增课程类别', requiresAuth: true },
        },
        {
          path: 'tasks/add',
          name: 'task-add',
          component: () => import('../views/AddTaskView.vue'),
          meta: { title: '新增课程任务', requiresAuth: true },
        },
        {
          path: 'courses/:id',
          name: 'course-detail',
          component: () => import('../views/CourseDetailView.vue'),
          meta: { title: '课程详情' },
        },
      ],
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      redirect: '/',
    },
  ],
  scrollBehavior() {
    return { top: 0 };
  },
});

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();
  if (to.meta?.requiresAuth && !authStore.isLoggedIn) {
    next({ name: 'login', query: { redirect: to.fullPath } });
    return;
  }
  if (to.name === 'login' && authStore.isLoggedIn) {
    next({ name: 'home' });
    return;
  }
  if (to.meta?.title) {
    document.title = `课程学习平台 - ${to.meta.title}`;
  } else {
    document.title = '课程学习平台';
  }
  next();
});

export default router;
